package com.aididi.collection;

/**
 * @Auther: zx.xu
 * @Description:    链表类
 */
public class ListNode {
    //头结点
    private Node head;
    //尾节点
    private Node tail;
    //大小
    private int size = 0;

    public ListNode() {
        head = new Node();
        tail = new Node();
        head.next =null;
        tail.pre = null;
    }

    public boolean empty() {
        if (head.next == null) {
            return true;
        }
            return false;
    }

    //找到所找下标节点的前一个节点
     public Node findpre(int index){
        Node rnode = head;
        int dex = -1;
        while(rnode.next != null){
            //找到了插入节点的上一个节点
            if( dex== index - 1){
            return rnode;
            }
            rnode = rnode.next;
            dex++;
        }
        return null;
     }

    public Node findthis(int index){
        Node rnode = head;
        //把rnode想象为指针，dex为指向的下标，这个地方很容易错，因为当指向最后一个节点时没有判断IF就跳出循环了
        int dex = -1;
        while(rnode.next != null){
            if(dex == index)
                return rnode;
            rnode = rnode.next;
            dex++;
        }
        if(dex == size - 1){
            return rnode;
        }
        //        Node test = new Node(new Students("haha",1,2));
        return null;
    }

    // 往链表末尾加入节点
    public void add(Object e) {
        Node node = new Node(e);
        Node rnode = head;
         //如果是空链表的话插入一个节点，这个节点的pre不能指向上一个节点，必须指空
         if (this.empty()) {
                 rnode.next = node;
               rnode.next.pre = null;
                 tail.pre = node;
                 size++;
            } else {
                 while (rnode.next != null) {
                     rnode = rnode.next;
                     rnode.next = node;
                     node.pre = rnode;
                     tail.pre = node;
                     size++;
                 }
             }
     }


}

/**
 * 双向链表节点类
 */
class Node{
    //数据域(你到时候要往节点里面储存的信息)
    public Object e;
    //下一个节点
    public Node next;
    //上一个节点
    public Node pre;

    public Node() {
    }

    public Node(Object e){
      this.e = e;
      next = null;
      pre = null;
    }


}
